window.onload = function() {
    /**环境设置 */
    // 本地环境
    // 铺脉动
    var _parentUrl = "http://localhost:8080";
    // 项目托管
    // var _parentUrl = "http://localhost:8088";
    // 测试/正式环境
    // var _parentUrl = '/'

    var _container = document.getElementById("svgcanvas");
    var _oss;
    var _companyCode = "";
    var _region = "oss-cn-beijing";
    var _percentage = 0;
    // 上传的文件
    var _file;
    var _svgCanvas = svgEditor.canvas;
    var _uploadCallback;

    // 默认svg模板
    var _defaultSvgTemplate =
        "//cmd-phd-public.oss-cn-beijing.aliyuncs.com/1056301000000000054/svg/201910/1571831922731-8718.svg";

    $("#upload-pic").change(function(e) {
        var target = e.target;
        _file = target.files[0];
        _uploadCallback = function(url) {
            // 上传成功后直接设置url
            _svgCanvas.setImageURL(url);
            _svgCanvas.setMode("select");
            $("#upload-image-popup").hide();
        };
        // 向父级发送消息，检查oss ticket
        sendMsg("getOssTicket", "");
    });
    // var prent
    window.addEventListener("message", event => {
        var data = JSON.parse(event.data);
        switch (data.type) {
            // oss Ticket
            case "ossTicket":
                _oss = data.data;
                doUpload(_uploadCallback);
                break;
            // 房源信息
            case "bindRoomInfo":
                bindSVGRoomInfo(data.data);
                break;
            case "companyCode":
                _companyCode = data.data;
                break;
            case "editSvgUrl":
                setDefaultSvgUrl(data.data);
                break;
            case "relationAuth":
                setRelationAuth(data.data);
                break;
            // 所有房间信息，用于删除掉已经绑定的无用的节点信息
            case "allRoomList":
                initSvgRoomShape(data.data);
                break;
        }
    });

    var addZero = function(str, length, char) {
        str = str || "";
        length = length || 2;
        char = char || "0";
        return str.toString().padStart(length, char);
    };

    // 删除掉已经绑定的无用的节点信息，已经删除的房源信息需要同步删除对应的图形信息
    function initSvgRoomShape(roomList) {
        var reg = /^\d{1,}$/;
        var pattern = new RegExp(reg);
        var roomNodes = $("#svgcontent [room_id]");
        for (var key in roomNodes) {
            if (pattern.test(key)) {
                var node = roomNodes[key];
                var room_id = node.getAttribute("room_id");
                if (!roomList.includes(room_id)) {
                    $(node).remove();
                }
            }
        }
    }

    function setRelationAuth(val) {
        if (!val) {
            $("#bind_house_source").remove();
        }
    }

    function setDefaultSvgUrl(url) {
        if (!url) {
            $("#choose-template-wrapper").show();
        } else {
            setDefaultTemplate(url);
        }
    }
    function sendMsg(type, msg) {
        parent.postMessage(
            JSON.stringify({
                type: type,
                data: msg
            }),
            _parentUrl
        );
    }
    function doUpload(_callback) {
        var client = new OSS.Wrapper({
            region: _region,
            accessKeyId: _oss.accessKeyId,
            accessKeySecret: _oss.accessKeySecret,
            stsToken: _oss.securityToken,
            bucket: _oss.bucket
        });

        var myDate = new Date();
        // 文件储存路径
        var datePath =
            myDate.getFullYear() + addZero(myDate.getMonth() + 1) + "/";
        var randomNum = 0;
        while (randomNum.length != 4) {
            randomNum = Math.floor(Math.random() * 10000).toString();
        }

        var filename = _file.name.split(".").pop();
        var randomName =
            new Date().getTime() + "-" + randomNum + "." + filename;
        var filePath = "";

        if (
            filename === "jpg" ||
            filename === "png" ||
            filename === "jpeg" ||
            filename == "gif"
        ) {
            filePath = "/pic/";
        } else if (filename === "svg") {
            filePath = "/svg/";
        } else {
            alert("错误的文件格式");
            return;
        }

        // 文件存储路径
        var fileStoragePath = _companyCode + filePath + datePath + randomName;

        client
            .multipartUpload(fileStoragePath, _file, {
                progress: function*(percentage) {
                    // 上传进度
                    _percentage = percentage;
                },
                headers: {
                    // 保证下载时还是原文件名，可设置值有inline 和 attachment，其中inline是将文件内容直接显示在页面而attachment则弹出对话框让用户下载
                    "Content-Disposition": `inline;filename=${encodeURIComponent(
                        _file.name
                    )}`
                }
            })
            .then(results => {
                var url =
                    "http://" +
                    _oss.bucket +
                    "." +
                    _region +
                    ".aliyuncs.com/" +
                    results.name;
                _callback(url);
            })
            .catch(err => {
                alert("上传文件失败，请重试！");
            });
    }

    function bindSVGRoomInfo(roomInfo) {
        // 房源id
        var room_id = roomInfo.room_id;
        // 显示文本
        var room_text = roomInfo.room_text;

        var selectElem = _svgCanvas.getSelectedElems();
        var old_room_id = selectElem[0].getAttribute("room_id");
        $(selectElem).attr({
            // fill: '#409eff', 不填充颜色，不然会在复制的时候一同拷贝进去，是个坑
            room_id: room_id
        });

        var roomParentId = $(selectElem).attr("id");
        var textNode = $("#svgcontent [room_parent_id=" + roomParentId + "]");
        // 新增关联房源
        if (!textNode.length) {
            if ($(selectElem)[0].nodeName === "rect") {
                var selectEle_x = $(selectElem).attr("x");
                var selectEle_y = $(selectElem).attr("y");
                var selectEle_w = $(selectElem).attr("width");
                var selectEle_h = $(selectElem).attr("height");
                var textId = _svgCanvas.getNextId();
                _svgCanvas.addSVGElementFromJson({
                    element: "text",
                    curStyles: true,
                    attr: {
                        x: selectEle_x + selectEle_w / 2,
                        y: selectEle_y + selectEle_h / 2,
                        id: textId,
                        fill: "#333",
                        "stroke-width": "0",
                        "font-size": 16,
                        "font-family": "serif",
                        "text-anchor": "middle",
                        "xml:space": "preserve",
                        opacity: "1",
                        room_type: "HOUSE-TEXT",
                        disabled: "true",
                        room_parent_id: roomParentId,
                        room_id: room_id
                    }
                });
                $("#" + textId).html(room_text);
                $(selectElem).attr("room_text_id", textId);
            } else if ($(selectElem)[0].nodeName === "path") {
                var nodeInfo = document
                    .getElementById($(selectElem).attr("id"))
                    .getBBox();

                var selectEle_x = nodeInfo.x;
                var selectEle_y = nodeInfo.y;
                var selectEle_w = nodeInfo.width;
                var selectEle_h = nodeInfo.height;
                var textId = _svgCanvas.getNextId();

                _svgCanvas.addSVGElementFromJson({
                    element: "text",
                    curStyles: true,
                    attr: {
                        x: selectEle_x + selectEle_w / 2,
                        y: selectEle_y + selectEle_h / 2,
                        id: textId,
                        fill: "#333",
                        "stroke-width": "0",
                        "font-size": 16,
                        "font-family": "serif",
                        "text-anchor": "middle",
                        "xml:space": "preserve",
                        opacity: "1",
                        room_type: "HOUSE-TEXT",
                        disabled: "true",
                        room_parent_id: $(selectElem).attr("id"),
                        room_id: room_id
                    }
                });

                $("#" + textId).html(room_text);
                $(selectElem).attr("room_text_id", textId);
            }
            sendMsg("changeRelationHouseList", { addId: room_id });
        } else {
            // 删除+新增关联房源
            textNode.html(room_text);
            textNode.attr("room_id", room_id);
            sendMsg("changeRelationHouseList", {
                delId: old_room_id,
                addId: room_id
            });
        }
    }

    // 生成需要上传的svg文件
    function getSvgFile() {
        var svg = '<?xml version="1.0"?>\n' + _svgCanvas.svgCanvasToString();
        return new File([svg], "room-svg.svg", {
            type: "image/svg+xml"
        });
    }

    function setDefaultTemplate(url) {
        // 请求svg数据
        $.ajax({
            url: url,
            type: "get",
            dataType: "html",
            success: function(data) {
                _svgCanvas.setSvgString(data);

                // 获取初始化绑定的房源列表
                var textNodes = $("text[room_type=HOUSE-TEXT]");
                var room_ids = textNodes.map(function(index) {
                    return textNodes[index].getAttribute("room_id");
                });

                // 项目托管用，初始化已经关联过的房间列表
                sendMsg("initRelatedRooms", room_ids);

                // 获取当前所有的房间列表，同步删除房源用
                sendMsg("getAllHouseList", "");
            }
        });
    }

    $("#SHAPE_IMAGE").click(function() {
        _svgCanvas.setMode("image");
        $(_container).trigger("mousedown");
        $(_container).trigger("mouseup");

        $("#upload-image-popup").show();
    });

    $("#upload-popup-close").click(function() {
        $("#upload-image-popup").hide();
        $("#SHAPE_IMAGE").removeClass("current-tool");
        _svgCanvas.setMode("select");
        _svgCanvas.deleteSelectedElements();
    });

    $("#choose-template-close").click(function() {
        $("#choose-template-wrapper").hide();
    });

    $("#freeRendering").click(function() {
        $("#choose-template-wrapper").hide();
    });

    $("#bind_house_source").click(function() {
        if (
            !$(this)
                .parent()
                .hasClass("disabled")
        ) {
            // 向父级发送消息，打开选择房间弹出框
            sendMsg("relatedHousing", "");
        }
    });

    $("#cancel_edit").click(function() {
        sendMsg("signOutSVGEdit", "");
    });

    $("#save_svg_file").click(function() {
        _file = getSvgFile();
        var textNodes = $("text[room_type=HOUSE-TEXT]");
        var room_ids = textNodes.map(function(index) {
            return textNodes[index].getAttribute("room_id");
        });
        _uploadCallback = function(url) {
            sendMsg("saveSvgFile", { url: url, room_ids: room_ids });
        };
        sendMsg("getOssTicket", "");
    });

    $("#importDefaultTemplate").click(function() {
        setDefaultTemplate(_defaultSvgTemplate);
        $("#choose-template-wrapper").hide();
    });

    $("#delete").click(function() {
        var selectElem = _svgCanvas.getSelectedElems();
        _svgCanvas.deleteSelectedElements();

        var room_type = $(selectElem).attr("room_type");
        var room_id = selectElem[0].getAttribute("room_id");
        switch (room_type) {
            // 相关联的HOUSE-TEXT也要删除掉
            case "HOUSE":
                $("#svgcanvas text[room_id=" + room_id + "]").remove();
                break;
            case "HOUSE-TEXT":
                $("#svgcanvas [room_id=" + room_id + "]").removeAttr("room_id");
                break;
        }
        sendMsg("changeRelationHouseList", { delId: room_id });
    });

    sendMsg("getCompanyCode", "");
    sendMsg("getEditSvgUrl", "");
    // 获取关联权限
    sendMsg("getRelationAuth", "");

    // 聚焦当前窗口
    window.focus();
};
